package pro.cherish.helloworld.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author 创建人：lys
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2020-6-15 lys 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：Client
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2020-6-15 
 */
@Slf4j
public class Client {
	public static void main(String[] args) throws InterruptedException, IOException {
		NioEventLoopGroup group = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();

		try {
			bootstrap.group(group).channel(NioSocketChannel.class)
					.handler(new ClientInitializer());

			Channel ch = bootstrap.connect("127.0.0.1", 8888).sync().channel();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				String line = bufferedReader.readLine();
				if (line == null) {
					break;
				}
				ChannelFuture lastWriteFuture = ch.writeAndFlush(line + "\r\n");
				if ("bye".equals(line.toLowerCase())) {
					ch.closeFuture().sync();
					break;
				}
				// 服务端没回复，此处就等待
				if (lastWriteFuture != null) {
					lastWriteFuture.sync();
				}
			}
		}finally {
			group.shutdownGracefully();
		}
	}
}
